package com.myapp.myhome.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.myapp.myhome.R;
import com.myapp.myhome.utils.ACache;
import com.myapp.myhome.utils.MyPreferences;
import com.myapp.myhome.view.RoundImageView;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class MyGridAdapter extends BaseAdapter {

	LayoutInflater layout;
	MyViewHolder holder;
	Context context;
	ArrayList<String> list_names = new ArrayList<String>();
	ArrayList<Bitmap> list_imgs = new ArrayList<Bitmap>();
	Set<String> siteno = new HashSet<String>();
	private ACache mCache;
	MyPreferences preferences;

	// 现在要想办法取得这些数据,然后保存下来
	String[] ss = { "群英", "李榕", "金玉", "毅华", "庄宏展" };

	public MyGridAdapter(Context context) {
		layout = LayoutInflater.from(context);
		preferences = new MyPreferences(context);
		mCache = ACache.get(context);
		this.context = context;
		setList();
	}

	public void setList() {
		siteno = preferences.getList("302home");
		list_names = new ArrayList<String>(siteno);
		for (int i = 0; i < siteno.size(); i++) {
			Bitmap testBitmap = mCache.getAsBitmap(list_names.get(i));
			if (testBitmap == null) {
				testBitmap = BitmapFactory.decodeResource(
						context.getResources(), R.drawable.tx_no);// 要是没有头像的话就是用这个头像

			}
			list_imgs.add(testBitmap);
		}
	}
	
	// 拿到头像 ---理论上使用bitmap
	public void setImgs(ArrayList<Bitmap> list_imgs) {
		this.list_imgs = list_imgs;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list_names.size() == 0 ? ss.length : list_names.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		if (convertView == null) {
			convertView = layout.inflate(R.layout.main_grid_item, null);
			holder = new MyViewHolder(convertView);
			convertView.setTag(holder);
		} else {
			holder = (MyViewHolder) convertView.getTag();
		}

		holder.mTextView.setText(list_names.get(position));
		// holder.img_touxiang.setImageResource(imgs[position]);
		holder.img_touxiang.setImageBitmap(list_imgs.get(position));
		return convertView;
	}

	class MyViewHolder {
		TextView mTextView;
		ImageView img_choice;
		RoundImageView img_touxiang;

		public MyViewHolder(View view) {
			mTextView = (TextView) view.findViewById(R.id.grid_item_text_name);
			img_choice = (ImageView) view
					.findViewById(R.id.grid_item_img_choice);
			img_touxiang = (RoundImageView) view
					.findViewById(R.id.grid_item_img_touxiang);
		}

	}

}
